from flask import Flask,render_template,request,flash,session,redirect,url_for
from forms import RegistForm,LoginForm,AddinForm
import config
from exts import db
from datetime import datetime
from flask_paginate import Pagination,get_page_parameter

app = Flask(__name__)
app.config['SECRET_KEY'] = '123456'
app.config.from_object(config)
db.init_app(app)

@app.route('/',methods=['GET','POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')

    if request.method == 'POST':
        form = LoginForm(request.form)
        username = form.username.data
        password = form.password.data
        cmsuser = Cmsuser.query.filter_by(username=username, password=password).first()
        user = Users.query.filter_by(username=username, password=password).first()
        if cmsuser:
            session["name"] = cmsuser.username
            session["online"] = '管理员在线状态'
            timeymd = "".join(str(datetime.now()).split(" ")[0])
            loginvistor = Loginvistor.query.filter_by(timeymd = timeymd).first()
            session["timeymd"] = timeymd
            if loginvistor:
                times = loginvistor.times
                session["times"] = times
                return  render_template("cmsindex.html",post_name = session["name"],online = session["online"],times = times,timeymd = timeymd)
            else:
                times = 0
                session["times"] = times
                return render_template("cmsindex.html", post_name=session["name"], online=session["online"],times=times, timeymd=timeymd)
        if user:
            session["name"] = user.username
            session["online"] = '在线状态'
            time = datetime.now()
            ip = request.remote_addr
            timeymd = "".join(str(datetime.now()).split(" ")[0])
            loginvistor = Loginvistor.query.filter_by(timeymd = timeymd).first()
            if loginvistor:
                loginrecord = Loginrecord.query.filter_by(username = session["name"],timeymd = timeymd).first()
                if loginrecord:
                    pass
                else:
                    loginvistor.times = loginvistor.times+1
                    db.session.commit()
            else:
                loginrecord = Loginrecord.query.filter_by(username=session["name"],timeymd = timeymd).first()
                if loginrecord:
                    pass
                else:
                    loginvistor = Loginvistor(times = 1,timeymd = timeymd)
                    db.session.add(loginvistor)
                    db.session.commit()
            loginrecord = Loginrecord(username=session["name"], time=time, ip=ip, timeymd=timeymd)
            db.session.add(loginrecord)
            db.session.commit()
            article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
            newlist = []
            for i in article:
                newlist.append(i)
            return render_template("article.html",list = newlist,post_name = session["name"],online = session["online"])
        else:
            error = '用户名或者密码错误'
            return render_template('article.html',error = error)


@app.route('/article/')
def article():
    article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
    newlist = []
    for i in article:
        newlist.append(i)
    # if session["name"]:
        post_name = session["name"]
        online = session["online"]
    # else:
    #     post_name = "当前状态"
    #     online = "未登录"
    return render_template('article.html',list = newlist,post_name = post_name,online = online)

@app.route('/regist/',methods=['GET','POST'])
def regist():
    if request.method =='GET':
        return render_template('regist.html')
    if request.method =='POST':
        form = RegistForm(request.form)
        username = form.username.data
        password1 = form.password1.data
        password2 = form.password2.data
        email = form.email.data
        tel = form.tel.data
        sex = request.form.get('sex')
        # state = "0"
        if password1 !=password2:
            error_name = '两次密码填写不一样'
            return render_template('regist.html',error_name=error_name)
        else:
            user = Users.query.filter(Users.username == username).first()
            if user:
                error_password = '用户名字已经存在'
                exist_name = username
                return render_template('regist.html', error_password = error_password ,exist_name = exist_name)
            else:
                if sex == '男':
                    sex=1
                    user=Users(username=username,password=password1,email=email,tel=tel,sex=sex)
                    db.session.add(user)
                    db.session.commit()
                if sex == '女':
                    sex=0
                    user=Users(username=username,password=password1,email=email,tel=tel,sex=sex)
                    db.session.add(user)
                    db.session.commit()
                return redirect(url_for('login'))

@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    if request.method == 'POST':
        form = LoginForm(request.form)
        username = form.username.data
        password = form.password.data
        cmsuser = Cmsuser.query.filter_by(username=username, password=password).first()
        user = Users.query.filter_by(username=username, password=password).first()
        if cmsuser:
            session["name"] = cmsuser.username
            session["online"] = '管理员在线状态'
            timeymd = "".join(str(datetime.now()).split(" ")[0])
            loginvistor = Loginvistor.query.filter_by(timeymd=timeymd).first()
            session["timeymd"] = timeymd
            if loginvistor:
                times = loginvistor.times
                session["times"] = times
                return render_template("cmsindex.html", post_name=session["name"], online=session["online"],
                                       times=times, timeymd=timeymd)
            else:
                times = 0
                session["times"] = times
                return render_template("cmsindex.html", post_name=session["name"], online=session["online"],
                                       times=times, timeymd=timeymd)
        if user:
            session["name"] = user.username
            session["online"] = '在线状态'
            time = datetime.now()
            ip = request.remote_addr
            timeymd = "".join(str(datetime.now()).split(" ")[0])
            timeymd = "".join(str(datetime.now()).split(" ")[0])
            loginvistor = Loginvistor.query.filter_by(timeymd=timeymd).first()
            if loginvistor:
                print(1)
                loginrecord = Loginrecord.query.filter_by(username=session["name"], timeymd=timeymd).first()
                if loginrecord:
                    pass
                else:
                    loginvistor.times = loginvistor.times + 1
                    db.session.commit()
            else:
                print(2)
                loginrecord = Loginrecord.query.filter_by(username=session["name"], timeymd=timeymd).first()
                if loginrecord:
                    print(21)
                else:
                    loginvistor = Loginvistor(times=1, timeymd=timeymd)
                    db.session.add(loginvistor)
                    db.session.commit()
            loginrecord = Loginrecord(username=session["name"], time=time, ip=ip,timeymd = timeymd)
            db.session.add(loginrecord)
            db.session.commit()
            article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
            newlist = []
            for i in article:
                newlist.append(i)
            return render_template("article.html",list = newlist,post_name = session["name"],online = session["online"])
        else:
            error = '用户名或者密码错误'
            return render_template('login.html',error = error)

@app.route('/information/')
def information():
    post_name = session["name"]
    online = session["online"]
    user = Users.query.filter_by(username = post_name).first()
    if user:
        username = user.username
        email = user.email
        tel = user.tel
        sql_sex = user.sex
        if sql_sex == 1:
            sex = '男'
        else:
            sex = '女'
        post_user = {
            'username':username,
            'email':email,
            'tel':tel,
            'sex':sex,
        }
        information =Usersinformation.query.filter_by(uusername = post_name).first()
        if information:
            place = information.place
            edu = information.edu_background
            height = information.height
            weight = information.weight
            game = information.game
            age = information.age
            character = information.character
            hobby = information.hobby
            post_information = {
                'place':place,
                'edu':edu,
                'age':age,
                'height':height,
                'weight':weight,
                'game':game,
                'character':character,
                'hobby':hobby,
            }
            img1 = Usersimg.query.filter_by(uusername = post_name).first()
            if img1:
                pass
                # post_img = img1.img.decode('utf-8')

            else:
                post_img = '暂无头像'
            return render_template("information.html", post_name=post_name, online=online, **post_user,**post_information,post_img = post_img)

        else:
            post_information = {
                'place': '无',
                'edu': '无',
                'height': '无',
                'age':'无',
                'weight': '无',
                'game': '无',
                'character': '无',
                'hobby': '无',
            }
            img1 = Usersimg.query.filter_by(uusername=post_name).first()
            if img1:
                post_img = img1.img
            else:
                post_img = '暂无头像'
            return render_template("information.html",post_name =post_name,online =online,**post_user,**post_information,post_img = post_img)

@app.route('/addinformation/',methods=['GET','POST'])
def addinformation():
    if request.method == 'GET':
        # return '1'
        return render_template('addinformation.html')
    if request.method == 'POST':
        form = AddinForm(request.form)
        place = request.form.get('place')
        edu = request.form.get('edu')
        height = form.height.data
        weight = form.weight.data
        age = request.form.get('age')
        game = request.form.get('game')
        character = request.form.get('character')
        hobby = request.form.get('hobby')

        username = session["name"]
        # print(username)
        information1 = Usersinformation.query.filter_by(uusername = username).first()
        if information1:
            db.session.delete(information1)
            information2 = Usersinformation(place = place,edu_background= edu,height = height,weight = weight,game = game,character = character,
                                           hobby = hobby,age = age,uusername = username)
            db.session.add(information2)
            db.session.commit()
        else:
            information2 = Usersinformation(place=place, edu_background=edu, height=height, weight=weight, game=game,
                                            character=character,
                                            hobby=hobby, age = age,uusername=username)
            db.session.add(information2)
            db.session.commit()
        post_name = session["name"]
        online = '在线状态'
        article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
        newlist = []
        for i in article:
            newlist.append(i)
        return render_template('article.html',post_name = post_name,online = online,list = newlist)

@app.route('/addimg/',methods=['GET','POST'])
def addimg():
    if request.method == 'GET':
        return render_template('addimg.html')
    if request.method == 'POST':
        img = request.form.get('img')
        username = session["name"]
        userimg = Usersimg.query.filter_by(uusername=username).first()
        if userimg:
            db.session.delete(userimg)
            username = session["name"]
            img2 = Usersimg(img = img,uusername = username)
            db.session.add(img2)
            db.session.commit()
        else:
            username = session["name"]
            img2 = Usersimg(img=img, uusername=username)
            db.session.add(img2)
            db.session.commit()
        post_name = session["name"]
        online = '在线状态'
        article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
        newlist = []
        for i in article:
            newlist.append(i)
        return render_template('article.html',post_name = post_name,online = online,list = newlist)

@app.route('/sysselect')
def sysselect():
    post_name = session["name"]
    online = session["online"]
    username = session["name"]
    user1 = Usersinformation.query.filter_by(uusername=username).first()
    place1 = user1.place
    edu1 = user1.edu_background
    height1 = user1.height
    weight1 = user1.weight
    game1 = user1.game
    character1 = user1.character
    hobby1 = user1.hobby
    age1 = user1.age
    leftheight = height1-15
    rightheight = height1+15
    leftweight = weight1-15
    rightweight = weight1+15
    leftage = age1-5
    rightage = age1+5
    user2 = Usersinformation.query.filter_by(edu_background = edu1,place = place1, game = game1, character = character1, hobby = hobby1).all()
    # print(user2)
    if user2:
        newlist = []
        for i in user2:
                if i.height>leftheight and i.height<rightheight and i.weight>leftweight and i.weight<rightweight and i.age>leftage and i.age<rightage and i.uusername !=session["name"]:
                    newlist.append(i)
                else:
                    pass
        # print(newlist)
    return render_template('sysselect.html',list = newlist,post_name=post_name,online=online)

@app.route('/appointselect/',methods=['GET','POST'])
def appointselect():
    post_name = session["name"]
    online = session["online"]
    if request.method == 'GET':
        return render_template('appointselect.html',post_name=post_name,online=online)
    if request.method == 'POST':
        form = AddinForm(request.form)
        age1 = int(form.age.data)
        place1 = request.form.get('place')
        edu1 = request.form.get('edu')
        height1 = int(form.height.data)
        weight1 = int(form.weight.data)
        game1 = request.form.get('game')
        character1 = request.form.get('character')
        hobby1 = request.form.get('hobby')
        sex = request.form.get('sex')
        print(type(height1))
        # print(type(int(height1)))
        leftheight = height1 - 10
        rightheight = height1 + 10
        leftweight = weight1 - 10
        rightweight = weight1 + 10
        leftage = age1 - 5
        rightage = age1 + 5
        if sex == '女':
            selectsex = 0
        else:
            selectsex = 1
        user2 = Users.query.filter_by(sex = selectsex).all()
        user1 = Usersinformation.query.filter_by(edu_background = edu1,place = place1, game = game1, character = character1, hobby = hobby1).all()
        print(user2)
        if user1:
            print(1)
            newlist = []
            for i in user1:
                if i.height > leftheight and i.height < rightheight and i.weight > leftweight and i.weight < rightweight and i.age > leftage and i.age < rightage :
                    for j in user2:
                        if j.username == i.uusername:
                            newlist.append(i)
                else:
                    print(2)
        print(newlist)
        return render_template('appointselect2.html', list=newlist,post_name=post_name,online=online)

@app.route('/sendmessage/',methods=['GET','POST'])
def sendmessage():
    post_name = session["name"]
    online = session["online"]
    if request.method == 'GET':
        return render_template('sendmessage.html',post_name=post_name,online=online)
    if request.method == 'POST':
        accept = request.form.get('accept')
        send = session["name"]
        content = request.form.get('content')
        time = datetime.now()
        state = '未读'
        message = Usersmessage(send = send,accept = accept,content = content,state = state,time = time)
        db.session.add(message)
        db.session.commit()
    post_name = session["name"]
    online = '在线状态'
    article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
    newlist = []
    for i in article:
        newlist.append(i)
    return render_template('article.html',post_name = post_name,online = online,list = newlist)

@app.route('/acceptmessage/')
def acceptmessage():
    accept = session["name"]
    post_name = session["name"]
    online = session["online"]
    message = Usersmessage.query.filter_by(accept =accept).all()
    if message:
        newlist = []
        for i in message:
            newlist.append(i)
    return render_template('acceptmessage.html',list = newlist,post_name=post_name,online=online)

@app.route('/acceptmessage2/')
def acceptmessage2():
    accept = session["name"]
    post_name = session["name"]
    online = session["online"]
    message = Usersmessage.query.filter_by(accept =accept,state ='未读').all()
    if message:
        newlist = []
        for i in message:
            i.state = '已读'
            db.session.commit()
            newlist.append(i)
    return render_template('acceptmessage2.html',list = newlist,post_name=post_name,online=online)

@app.route('/addarticle/',methods=['GET','POST'])
def addarticle():
    post_name = session["name"]
    online = session["online"]
    if request.method == 'GET':
        return render_template('addarticle.html',post_name=post_name,online=online)
    if request.method == 'POST':
        articlecontent = request.form.get('content')
        username = session["name"]
        time = datetime.now()
        article = Usersarticle(username = username,articlecontent = articlecontent,time = time)
        db.session.add(article)
        db.session.commit()
    post_name = session["name"]
    online = '在线状态'
    article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
    newlist = []
    for i in article:
        newlist.append(i)
    return render_template('article.html',post_name = post_name,online =online,list = newlist)

@app.route('/addcomment/<id>',methods=['GET','POST'])
def addcomment(id):
    if request.method == 'GET':
        return render_template('addcomment.html',id= id)
    if request.method == 'POST':
        username = session["name"]
        articlecomment = request.form.get('comment')
        time = datetime.now()
        comment = Userscomment(username = username,articleid =id,articlecomment = articlecomment,time = time)
        db.session.add(comment)
        print(id)
        article1 = Usersarticle.query.filter(Usersarticle.articleid == id).first()
        article1.articlecomment = articlecomment
        db.session.commit()
    post_name = session["name"]
    online = '在线状态'
    article = Usersarticle.query.order_by(db.desc(Usersarticle.time)).filter().all()
    newlist = []
    for i in article:
        newlist.append(i)
    return render_template('article.html',post_name = post_name,online = online,list = newlist)

@app.route('/selectcomment/<id>')
def selectcomment(id):
    article = Usersarticle.query.filter_by(articleid = id).first()
    username = article.username
    content = article.articlecontent
    time = article.time
    comment = Userscomment.query.filter_by(articleid = id).all()
    newlist = []
    if comment:
        for i in comment:
            newlist.append(i)
    return render_template("selectcomment.html",username = username,content = content,time = time,list = newlist)

@app.route('/cmsloginrecord/')
def cmsloginrecord():
    page = request.args.get(get_page_parameter(),type=int,default=1)
    post_name=session["name"]
    online=session["online"]
    timeymd = "".join(str(datetime.now()).split(" ")[0])
    loginrecord_times = Loginrecord.query.filter_by(timeymd = timeymd).count()
    post_times = int(loginrecord_times/10)
    if post_times>10:
        post_times=10
    loginrecord = Loginrecord.query.filter_by(timeymd = timeymd).paginate(page=page,per_page=10).items
    # newlist = []
    # for i in loginrecord:
    #     newlist.append(i)
    print(loginrecord)
    return render_template("cmsloginrecord.html",pagination = loginrecord,post_name=post_name,online=online,page=page,post_times=post_times)

@app.route('/cmselectarticle/',methods=['GET','POST'])
def cmselectarticle():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    article_times = Usersarticle.query.filter_by().count()
    post_times = int(article_times / 10)
    if post_times > 10:
        post_times = 10
    post_name = session["name"]
    online = session["online"]
    if request.method == 'GET':
        article = Usersarticle.query.filter_by().paginate(page=page,per_page=6).items
        # newlist = []
        # for i in article:
        #     newlist.append(i)
        return render_template("cmselectarticle.html",pagination=article,post_name=post_name,online=online,post_times=post_times,page=page)



    if request.method == 'POST':
        articleid = request.form.get("articleid")
        article = Usersarticle.query.filter_by(articleid = articleid).first()
        articleid = article.articleid
        username = article.username
        content = article.articlecontent
        time = article.time
        return render_template("cmselectarticle2.html",articleid = articleid,username = username,content = content,time = time,post_name=post_name,online=online)



# @app.route('/cmselectuser_select/<id>')
# def cmselectuser_select(id):
#     information = Usersinformation.query.filter_by(uusername = id).first()
#     age = information.age
#     place = information.place
#     edu = information.edu_background
#     height = information.height
#     weight = information.weight
#     game = information.game
#     character = information.character
#     hobby = information.hobby
#     post_information = {
#         "age":age,
#         "place":place,
#         "edu":edu,
#         "height":height,
#         "weight":weight,
#         "game":game,
#         "character":character,
#         "hobby":hobby,
#     }
#     return render_template("cmselectuser_select.html",**post_information,username = id)

@app.route('/cmselectarticle_delete/<id>')
def cmselectarticle_delect(id):
    post_name = session["name"]
    online = session["online"]
    article = Usersarticle.query.filter_by(articleid = id).first()
    db.session.delete(article)
    db.session.commit()
    comment = Userscomment.query.filter_by(articleid = id).all()
    for i in comment:
        db.session.delete(i)
        db.session.commit()


    # message = Usersmessage.query.filter_by(send = id).all()
    # if message:
    #     db.session.delete(message)
    #
    # message2 = Usersmessage.query.filter_by(accept=id).all()
    # if message2:
    #     db.session.delete(message2)
    #
    #
    # comment = Userscomment.query.filter(username = id).all()
    # if comment:
    #     db.session.delete(comment)
    #
    # article = Usersarticle.query.filter(username = id).all()
    # if article:
    #     db.session.delete(article)
    page = request.args.get(get_page_parameter(), type=int, default=1)
    article_times = Usersarticle.query.filter_by().count()
    post_times = int(article_times / 10)
    if post_times > 10:
        post_times = 10
    if request.method == 'GET':
        article = Usersarticle.query.filter_by().paginate(page=page, per_page=10).items
        # newlist = []
        # for i in article:
        #     newlist.append(i)
    return render_template("cmselectarticle.html", pagination=article, post_name=post_name, online=online,
                               post_times=post_times, page=page)













class Users(db.Model):
    __tablename__ = 'user'
    username = db.Column(db.String(50),nullable=False,primary_key=True,unique=True)
    password = db.Column(db.String(50),nullable=False)
    email = db.Column(db.String(50),nullable=False)
    tel = db.Column(db.String(50),nullable=False)
    sex = db.Column(db.Integer,nullable=False)
    # state = db.Column(db.Integer,nullable=False)
    # state = db.Column(db.Integer,nullable=False)

class Usersinformation(db.Model):
   __tablename__ = 'information'
   id = db.Column(db.Integer, autoincrement=True,primary_key=True)
   age = db.Column(db.Integer, nullable=False)
   place = db.Column(db.String(50),nullable=False)
   edu_background = db.Column(db.String(50),nullable=False)
   height = db.Column(db.Integer)
   weight = db.Column(db.Integer)
   game = db.Column(db.String(50),nullable=False)
   character = db.Column(db.String(50),nullable=False)
   hobby = db.Column(db.String(50),nullable=False)
   uusername = db.Column(db.String(50),db.ForeignKey('user.username'))
   users = db.relationship('Users', backref='informartions')

   # def __repr__(self):
   #     return "用户名%s 体重%s 身高%s 性格%s 教育背景%s" %(self.uusername,self.weight,self.height,self.character,self.edu_background)

class Usersimg(db.Model):
    __tablename__ = 'img'
    id = db.Column(db.Integer, autoincrement=True,primary_key=True)
    img =db.Column(db.String(50))

    uusername = db.Column(db.String(50), db.ForeignKey('user.username'))

class Usersmessage(db.Model):
    __tablename__ = 'message'
    id = db.Column(db.Integer, autoincrement=True,primary_key=True)
    send = db.Column(db.String(50),nullable=False)
    accept = db.Column(db.String(50),nullable=False)
    content = db.Column(db.String(150),nullable=False)
    state = db.Column(db.String(50),nullable=False)
    time = db.Column(db.DateTime,nullable=False)

class Usersarticle(db.Model):
    __tablename__ = 'article'
    username = db.Column(db.String(50),nullable=False)
    articleid = db.Column(db.Integer, autoincrement=True,primary_key=True)
    articlecontent = db.Column(db.String(150),nullable=False)
    articlecomment = db.Column(db.String(150))
    time = db.Column(db.DateTime, nullable=False)

class Userscomment(db.Model):
    __tablename__ = 'comment'
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    username = db.Column(db.String(50),nullable=False)
    articleid = db.Column(db.Integer, nullable=False)
    articlecomment = db.Column(db.String(150), nullable=False)
    time = db.Column(db.DateTime, nullable=False)

    # uarticleid = db.Column(db.Integer, db.ForeignKey('article.articleid'))

class Cmsuser(db.Model):
    __tablename__ = 'cmsuser'
    username = db.Column(db.String(50),nullable=False,primary_key=True)
    password = db.Column(db.String(50),nullable=False)

class Loginrecord(db.Model):
    __tablename__ = 'loginrecord'
    id = db.Column(db.Integer,nullable=False,autoincrement=True,primary_key=True)
    username = db.Column(db.String(50),nullable=False)
    time = db.Column(db.DateTime, nullable=False)
    ip = db.Column(db.String(50),nullable=False)
    timeymd = db.Column(db.String(50),nullable=False)

class Loginvistor(db.Model):
    __tablename__ = 'loginvistor'
    id = db.Column(db.Integer,nullable=False,autoincrement=True,primary_key=True)
    times = db.Column(db.Integer,nullable=False,default = 0)
    timeymd = db.Column(db.String(50),nullable=False)

# db.drop_all(app=app)

# db.create_all(app=app)

if __name__ == '__main__':
    app.run()
